<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
        }
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background: radial-gradient(#1e1748, #181818);
            perspective: 1200px;
        }

        .card-box {
            
            width: 200px;
            border-radius: 4px;
            transform: rotateX(var(--rx, 0deg)) rotateY(var(--ry, 0deg));
            /* transition: .2s; */
        }

        .card-box:hover {
            /* box-shadow: -2px -2px 10px #949494,
            2px 2px 10px #414247; */
        }

        .card-img {
            display: block;
            width: 100%;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="card-box">
        <img class="card-img" src="./img/cardImg.png" alt="">
    </div>
</body>
<script>

    // x轴旋转范围
    let rotateXRange = [-20, 20]
    // y轴旋转范围
    let rotateYRange = [-10, 10]

    let optDom = document.querySelector('.card-box')

    // 获取旋转角度 角度范围 移动距离 总距离
    function getRotateDeg (range, value, length) {
        return (value / length) * (range[1] - range[0]) + range[0]
    }

    optDom.addEventListener('mousemove', (e) => {
        const { offsetX, offsetY } = e
        const { offsetWidth, offsetHeight } = optDom
        const ry = -getRotateDeg(rotateXRange, offsetX, offsetWidth)
        const rx = getRotateDeg(rotateYRange, offsetY, offsetHeight)
        optDom.style.setProperty('--rx', `${rx}deg`)
        optDom.style.setProperty('--ry', `${ry}deg`)
    })

    optDom.addEventListener('mouseleave', (e) => {
        // optDom.style.setProperty('--rx', `0deg`)
        // optDom.style.setProperty('--ry', `0deg`)
    })
</script>
</html>